package top.itaso.lib.net.interceptor;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.Buffer;
import top.itaso.lib.net.log.LogUtils;

/**
 * @Description:
 * @Author itsdf07
 * @E-Mail 923255742@qq.com
 * @Github https://github.com/itsdf07
 * @Date 2020/11/3
 */
class BodyInterceptor implements Interceptor {
    private static final String TAG = BodyInterceptor.class.getSimpleName();

    @Override
    public Response intercept(Chain chain) throws IOException {
        // 拦截请求，获取到该次请求的request
        Request request = chain.request();
        String method = request.method();//如：POST
        String host = request.url().host();//如：api.itaso.top
        String url = request.url().toString();//如：http://api.itaso.top/api/user/sendVerifyCode2Email
        boolean isHttps = request.url().isHttps();//如：false
        String scheme = request.url().scheme();//如：http
        LogUtils.logd("BodyInterceptor intercept: >>>>>>method=" + method + ",host=" + host + ",isHttps=" + isHttps + ",scheme=" + scheme + ",url=" + url);
        if ("POST".equals(method)) {
            if (request.body() instanceof RequestBody) {
                LogUtils.logd("BodyInterceptor intercept: >>>>>>当前为 RequestBody 数据请求");
                final Request.Builder builder = request.newBuilder();
                Buffer buffer = new Buffer();
                request.body().writeTo(buffer);
                JSONObject jsonBody = null;
                try {
                    jsonBody = new JSONObject(buffer.readByteString().utf8());
                    jsonBody.put("channel", "00001");
                    jsonBody.put("pkgName", "top.itaso.uiapp");
                    jsonBody.put("clientOs", 1);
                    jsonBody.put("version", "1.0.0");
                    RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonBody.toString());
                    builder.post(requestBody);
                    Response response = chain.proceed(builder.build());
                    return response;
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else if (request.body() instanceof FormBody) {//表达提交
                LogUtils.logd("BodyInterceptor intercept: >>>>>>当前为 FormBody 数据请求");
            } else {

            }
        } else if ("GET".equals(method)) {

        } else {

        }
        // 执行本次网络请求操作，返回response信息
        Response response = chain.proceed(request);
        LogUtils.logd("BodyInterceptor intercept: >>>>>>response.code=" + response.code());
        return response;
    }
}
